import os
import sys
sys.path.append('../')
from utility.hdf5 import HDF5
import numpy as np
#import h5py
import random
import time
from pathlib import Path
from sgfmill import sgf,boards,ascii_boards
doc='./sgfs/'


def list_all_file(fPath):
    fileList=os.listdir(fPath)
    file_list=[]
    for i in fileList:
        file_dir=Path(fPath+'/'+i)
        if file_dir.is_file():
            file_list.append(file_dir)
    return file_list







class sgf_parser():
    def __init__(self,filePath,h5file=None,mode='a'):
        with open(filePath,"rb") as f:
            self.game=sgf.Sgf_game.from_bytes(f.read())
        self.fileName=os.path.basename(filePath)
        self.winner=self.game.get_winner()
        self.boardsize=self.game.get_size()
        self.npboard=np.zeros((self.boardsize,self.boardsize))
        #self.datas=[]
        self.b=boards.Board(self.boardsize)
        self.h5file=HDF5(h5file,mode=mode)
    def setSamples(self,mode=0):   #解析sgf文件
        for index,node in enumerate(self.game.get_main_sequence()):
            who,point=node.get_move()
            if who is not None and point is not None:
                #b.play(point[0],point[1],who)
                data=(self.npboard,point,1 if who=='b' else -1,1 if self.winner.lower()=='b' else -1)    #需要保存的样本，[输入，输出，谁下，谁赢]
                if self.h5file is not None:
                    self.saveSamples(str(index),data,mode=mode)
                #self.datas.append(data)
                self.b.play(point[0],point[1],who)
                self.npboard=np.zeros((self.boardsize,self.boardsize))
                for i in self.b.board_points:
                    color=self.b.get(*i)
                    if color:
                        self.npboard[i]=1 if color=='b' else -1 #npboard的原点是左上角，sgfmill是左下角，所以生成的数据会是上下镜像
                #print(self.npboard)
                #print(ascii_boards.render_board(self.b))
                #input('press:')
                #self.npboard[point]=1 if who=='b' else -1 #npboard的原点是左上角，sgfmill是左下角，所以生成的数据会是上下镜像

    def saveSamples(self,dsetName,data,mode=0): #把数据保存到h5文件里,数据都是做过flatten后的平摊展开的数据
        if mode==1: #mode=1只保存胜利方的数据，mode=0保存黑白方的数据
            if data[2]!=data[3]:
                return
        sample_y=np.zeros((self.boardsize,self.boardsize))
        sample_y[data[1]]=1
        sample_y=sample_y.flatten()
        sample_x=data[0].flatten()
        npdata=np.vstack((sample_x,sample_y))   #合并成2行self.boardsize列数组
        grpName=self.fileName
        if not self.h5file.isGrpExist(grpName):
            self.h5file.add_group(grpName)
            self.h5file.set_grp_attrs(grpName,'winner',data[3]) #如果第一次建，就设置该局的胜利方
            self.h5file.set_grp_attrs(grpName,'size',self.boardsize)    # 记录棋盘的大小
        self.h5file.add_dataset(grpName,dsetName,npdata)
        self.h5file.set_dset_attrs(grpName,dsetName,'player',data[2])
    def showGame(self): #打印棋盘
        for node in self.game.get_main_sequence():
            who,point=node.get_move()
            if who is not None and point is not None:
                self.b.play(point[0],point[1],who)
        print(ascii_boards.render_board(self.b))

    def closeParser(self):  #关闭句柄
        self.h5file.closeH5()

if __name__ == "__main__":
    doc='./sgfs/'
    file_lists=list_all_file(doc)
    h5file='game_recorders_'+str(random.randint(1,10000000))+'.h5'
    since=time.time()
    for i in file_lists:
        try:
            one_sgf=sgf_parser(i,h5file)
            one_sgf.setSamples()
            #one_sgf.showGame()
            one_sgf.closeParser()
        except:
            print("error,filename:",i)
        else:
            None
    print(time.time()-since)
